package com.webserver.core;

import com.webserver.http.EmptyRequestException;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;

/**
 * 线程任务负责与指定的客户端进行HTTP交互
 * 按照HTTP协议的交互规则，与浏览器采取一问一答。
 *
 * @author Chen
 */
public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            // 1.解析请求和创建响应对象
            HttpServletRequest request = new HttpServletRequest(socket);
            HttpServletResponse response = new HttpServletResponse(socket);

            /*
             * 常用的相对路径：类加载路径
             * 定位类加载路径
             * 任何当前项目中的类的类名，通常在哪个类中需要访问类加载路径就用哪个类
             * 类名.class.getClassLoader().getResource(".")
             * 类加载路径: target/classes
             */
            // 2.处理请求
            DispatcherServlet servlet = DispatcherServlet.getInstance();
            servlet.service(request, response);

            // 3.发送响应
            response.response();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (EmptyRequestException ignored) {
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
